/*
 * Copyright 2011-2012 OpenAjax Alliance
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/**
 * @file sidebar-rule-summary.js
 *
 * @desc Supports the sidebar showing rule summary information for a list if cache items 
 */

Components.utils.import("resource://oaa-cache-inspector/cache-inspector-common.js");

/* ---------------------------------------------------------------- */
/*            OAA_CI and OAA_CI.RuleResultSummary Object                  */ 
/* ---------------------------------------------------------------- */

if (typeof OAA_CI === "undefined") {
  var OAA_CI = {};
}

if (typeof OAA_CI.RuleSummaryView === "undefined") {
  OAA_CI.RuleSummaryView = {};
}

/* ---------------------------------------------------------------- */
/*                  Rule Summary View Control Functions             */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_CI.RuleSummaryView.init
 *
 * @desc Creates references for XUL controls
 */
 
OAA_CI.RuleSummaryView.init = function () {

  var doc = window.document;

  this.nls_strings               = doc.getElementById('ID_STRINGBUNDLE_LIST');
  
  this.vbox_rule_summary         = doc.getElementById('ID_VBOX_RULE_SUMMARY_VIEW');

  this.label_rule_summary        = doc.getElementById('ID_LABEL_RULE_SUMMARY_NAME');

  this.hbox_expand_collapse      = doc.getElementById('ID_HBOX_RULE_SUMMARY_EXPAND');
  
  this.tree_rule_summary             = doc.getElementById('ID_TREE_RULE_SUMMARY');
  this.treechildren_rule_summary     = doc.getElementById('ID_TREECHILDREN_RULE_SUMMARY');
  this.treecol_rule_summary_primary  = doc.getElementById('ID_TREECOL_RULE_DESCRIPTION');
  
  this.textbox_rule_result_message   = doc.getElementById('ID_TEXTBOX_RULE_SUMMARY_MESSAGE');
  
  this.button_rule_info          = doc.getElementById('ID_BUTTON_RULE_SUMMARY_RULE_INFORMATION');
  
  this.rule_summary_items = [];
  this.rule_summary_item  = null;
  
  this.sidebar_name = "no name";
  
};

/**
 * @function OAA_CI.RuleSummaryView.hide
 *
 * @desc Hides the XUL elements of the rule results view
 */
 
OAA_CI.RuleSummaryView.hide = function () {
  this.vbox_rule_summary.hidden = true;
};

/**
 * @function OAA_CI.RuleSummaryView.show
 *
 * @desc Shows the rule results summary view
 */
 
OAA_CI.RuleSummaryView.show = function () {
  this.vbox_rule_summary.hidden = false;
};

/**
 * @function OAA_CI.RuleSummaryView.clear
 *
 * @desc Clears the rule results summary view with a "updating" message
 */
 
OAA_CI.RuleSummaryView.clear = function () {

  if (!this.treechildren_rule_summary) return;
  if (!this.nls_strings) return;
  
  OAA_CI.removeChildNodes(this.treechildren_rule_summary);  
  OAA_CI.addTreeItemMessage(this.treechildren_rule_summary, this.nls_strings.getString('updating'), '', 1);
  this.ruleButtonClear();
  OAA_CI.RuleResultView.clear();

};

/**
 * @function OAA_CI.RuleSummaryView.update
 *
 * @desc Initializes and shows the rule results summary view
 */
  
OAA_CI.RuleSummaryView.update = function (sidebar_name) {
     
  function addRuleResultItem(treechildren, rule_summary_item) {
  
//     if (rule_summary_item.rule_result) OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Filtered rule result item: " + rule_summary_item.rule_result.getRule());
//     else OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Filtered group result: " + rule_summary_item.group_id);
    
     if (rule_summary_item.rule_result) rule_summary_item.position = position++;
     
     OAA_CI.RuleSummaryView.rule_summary_items.push(rule_summary_item);

     var cache_id = rule_summary_item.cache_id;     
     
     var description          = "no description";
     var wcag20_sc_level      = "";
     var required             = "";
     var nls_implementation_level = null;
     var rule_group           = false;
 
     if (rule_summary_item.rule_result) {
       description               = rule_summary_item.rule_result.getRuleSummary();
       required                 = (rule_summary_item.rule_result.rule_mapping.type === OpenAjax.a11y.RULE.REQUIRED) ? boolean_values.true_value : boolean_values.false_value;
       wcag20_sc_level          = rule_summary_item.rule_result.rule.getNLSWCAG20Level();
       
       implementation_level     = rule_summary_item.getImplementationLevel();
       nls_implementation_level = rule_summary_item.getNLSImplementationLevel();
     }
     else {
       description          = rule_summary_item.title;
       
       if (rule_summary_item.getNumberOfRules) description += " (" + rule_summary_item.getNumberOfRules() + " rules)";
       
       nls_implementation_level = rule_summary_item.getNLSImplementationLevel();
       implementation_level     = rule_summary_item.getImplementationLevel();
       rule_group = true;
     }
          
//     OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("     Cache ID: " + cache_id);
//     OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("  Description: " + description);
//     OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("     Required: " + required);
//     OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("   Imp. Level: " + rule_summary_item.getImplementationLevel());
//     OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("   NLS Imp. Level: " + nls_implementation_level.label + " (" + nls_implementation_level.abbrev + ")");
     
     var treeitem = document.createElement('treeitem');
     var treerow  = document.createElement('treerow');
        
     var treecell  = document.createElement('treecell');
     treecell.setAttribute('value', cache_id);
     treecell.setAttribute('label', description);
     if (rule_group) treecell.setAttribute('properties', 'rule_group'); 
     treerow.appendChild(treecell);

     treecell = document.createElement('treecell');
     treecell.setAttribute('label', required); 
     if (required.length) treecell.setAttribute('properties', required.toLowerCase()); 
     treerow.appendChild(treecell);

     treecell = document.createElement('treecell');
     treecell.setAttribute('label', wcag20_sc_level); 
     treerow.appendChild(treecell);

//     OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Position: " + position + " Sort Level: " + rule_summary_item.implementation_level_sort + " (" + rule_summary_item.manual_check_count + ")");

     treecell = document.createElement('treecell');
     treecell.setAttribute('label',       nls_implementation_level.label); 
     treecell.setAttribute('properties',  nls_implementation_level.style); 
     treerow.appendChild(treecell);

     if ((rule_summary_item.manual_checks_count && rule_summary_item.manual_checks_count > 0) ||
         (implementation_level != IMPLEMENTATION_LEVEL.NOT_APPLICABLE && 
          implementation_level != IMPLEMENTATION_LEVEL.RULE_DISABLED)) {       
       treecell = document.createElement('treecell');
       treecell.setAttribute('label', rule_summary_item.manual_checks_count); 
       if (rule_summary_item.manual_checks_count > 0) treecell.setAttribute('properties',  'manual_check'); 
       else treecell.setAttribute('properties',  'zero'); 
       treerow.appendChild(treecell);
     }
     else {
       treecell = document.createElement('treecell');
       treecell.setAttribute('label',       ''); 
       treerow.appendChild(treecell);     
     }
       

     treeitem.appendChild(treerow);

     var rule_summary_items     = [];
     var rule_summary_items_len = 0;

     if (rule_summary_item.filtered_rule_results) {
       rule_summary_items = rule_summary_item.filtered_rule_results;
       rule_summary_items_len = rule_summary_items.length;
     }   
     else {
       if (rule_summary_item.filtered_rule_results_groups) {
         rule_summary_items     = rule_summary_item.filtered_rule_results_groups;
         rule_summary_items_len = rule_summary_items.length;
       }  
     }
     
     if (rule_summary_items && rule_summary_items_len) {
       
       var sub_treechildren = document.createElement('treechildren');
     
       for (var i = 0; i < rule_summary_items_len; i++) addRuleResultItem(sub_treechildren, rule_summary_items[i]);
     
       treeitem.appendChild(sub_treechildren);
       treeitem.setAttribute('container', 'true');        
       treeitem.setAttribute('open',      'true');        
     }
     
     treechildren.appendChild(treeitem);
        
  }

  var boolean_values = OpenAjax.a11y.cache_nls.getCacheNLS().boolean_values;
  
  var IMPLEMENTATION_LEVEL = OpenAjax.a11y.IMPLEMENTATION_LEVEL;
  
  var nls_strings  = this.nls_strings;
  var treechildren = this.treechildren_rule_summary;
  var tree         = this.tree_rule_summary;
  var position = 1;
  
  var prefs = OAA_WEB_ACCESSIBILITY_PREF.util.getPreferences();
  
  this.sidebar_name = sidebar_name;
  
//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("WCAG 2.0 Level: " + prefs.wcag20_level);
  
  var RULE_GROUP = OpenAjax.a11y.RULE_GROUP;

  if (!treechildren || !nls_strings) return;
  
  if (!OAA_CI.ruleset) OAA_CI.updateEvaluation();

  this.label_rule_summary.setAttribute('value', this.sidebar_name);

  var rr_summary;
  var rr_items;
  var rr_items_len;
  
  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIWebNavigation)
  .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  .rootTreeItem
  .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIDOMWindow);

//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Sidebar Name: " + mainWindow.oaa_sidebar_name + "  Option: " + mainWindow.oaa_sidebar_option);

  this.filtered_rule_summary  = OAA_CI.ruleset.getFilteredRuleResultsByRuleSummary(mainWindow.oaa_sidebar_option, mainWindow.oaa_sidebar_name, prefs.wcag20_level, prefs.show_results_filter_value);

  if (!this.filtered_rule_summary) {
    this.clear();
    return;
  };

  this.hbox_expand_collapse.hidden = false;
  this.treecol_rule_summary_primary.setAttribute('primary', 'true');

  rr_summary   = this.filtered_rule_summary;
  rr_items     = rr_summary.filtered_rule_results_groups;
  rr_items_len = rr_items.length;

  OAA_CI.removeChildNodes(treechildren);
  
  this.rule_summary_items = [];
  this.rule_summary_item  = null;
  
  var index = 1;

//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("RULE RESULT SUMMARY: " + rr_items + " (" + rr_items_len + ")");

  if (rr_items) {
  
    var rr_item;
    var props;

    if (rr_items_len === 0) {
      OAA_CI.addTreeItemMessage(treechildren, nls_strings.getString('noRuleResults'), '');
    }
    else {
    
      for (var i = 0; i <  rr_items_len; i++) { 
        rr_item = rr_items[i];
        addRuleResultItem(treechildren, rr_item);
      }
      
    }
  }  
  else {
    OAA_CI.addTreeItemMessage(treechildren, nls_strings.getString('noRuleResults'), '');
  }
  
  this.rule_summary_item = null;
      
  this.ruleButtonClear();
  OAA_CI.RuleResultView.clear();
  
};

/**
 * @function OAA_CI.RuleSummaryView.onSelect
 *
 * @desc Updates node results when a cache item is selected
 */
 
OAA_CI.RuleSummaryView.onSelect = function () {

  var tree_rule_summary = OAA_CI.RuleSummaryView.tree_rule_summary;
  var rr_items          = this.rule_summary_items;
  var rr_items_len      = rr_items.length;
  
  this.rule_summary_item = null;

  if (tree_rule_summary) {
  
    var index = tree_rule_summary.currentIndex;

    var cache_id = OAA_CI.getCacheIdFromTree(tree_rule_summary, index);
 
    if (cache_id) {

      for (var i = 0; i < rr_items_len; i++ ) {
        var rr_item = rr_items[i];
        if (cache_id == rr_item.cache_id) {
          this.rule_summary_item = rr_item;
          break;    
        }    
      } // end loop

      // check if a rule result object

      OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Filtered Rule Result Item: " + this.rule_summary_item);  

      if (this.rule_summary_item && this.rule_summary_item.rule_result) {
        OAA_CI.RuleResultView.update(this.rule_summary_item);   
        OAA_CI.RuleSummaryView.ruleButtonUpdate(this.rule_summary_item);
      }
      else {
        OAA_CI.RuleSummaryView.ruleButtonClear();  
        OAA_CI.RuleResultView.clear();
      }
    }  
    else {
      OAA_CI.RuleSummaryView.ruleButtonClear();  
      OAA_CI.RuleResultView.clear();
    }
  } 
};

/**
 * @function OAA_CI.RuleSummaryView.showRuleInformation
 *
 * @desc Show information about the currently selected rule 
 */
 
OAA_CI.RuleSummaryView.showRuleInformation = function () {

  if (this.rule_summary_item && this.rule_summary_item.rule_result) { 
    OAA_CI.showRulePropertiesDialog(this.rule_summary_item.rule_result);
  }
};



/* ---------------------------------------------------------------- */
/*                    Rule Result Information Button                */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_CI.RuleSummaryView.ruleButtonClear
 *
 * @desc Clears the rules in the rules tabs
 */
 
OAA_CI.RuleSummaryView.ruleButtonClear = function () {

  if (this.nls_strings && this.button_rule_info) {
    this.button_rule_info.setAttribute("label", this.nls_strings.getString('rule') + ' ' + this.nls_strings.getString('information'));
    this.button_rule_info.setAttribute('tooltiptext', this.nls_strings.getString('noRuleSelected'));
    this.button_rule_info.setAttribute("disabled",    "true");
  }
  
  if (OAA_CI.rule_properties_dialog && 
      OAA_CI.rule_properties_dialog.rule_properties) {
    OAA_CI.rule_properties_dialog.rule_properties.clear();
  }

  if (this.textbox_rule_result_message) {
    this.textbox_rule_result_message.setAttribute('value', this.nls_strings.getString('noRuleSelected'));
  }
  
  this.rule_summary_item = null;

};

/**
 * @function OAA_CI.RuleSummaryView.ruleButtonUpdate
 *
 * @desc Updates the label of the show rule information button
 *
 * @param {FilteredRuleResult}  rule_summary_item  - filtered rule result object   
 */
 
OAA_CI.RuleSummaryView.ruleButtonUpdate = function (rule_summary_item) {

  var label;

  if (this.nls_strings && this.button_rule_info) {
  
    var rule_result = rule_summary_item.rule_result;
    
    if (rule_result.getRuleSummary) {
    
      label = this.nls_strings.getString('moreInformationRule') + ": " + rule_result.getRuleSummary();

      this.button_rule_info.setAttribute("label", this.nls_strings.getString('rule') + ' ' + rule_summary_item.position + ' ' + this.nls_strings.getString('information'));
      this.button_rule_info.setAttribute("tooltiptext",  label);
      this.button_rule_info.setAttribute("disabled", "false");

      if (OAA_CI.rule_properties_dialog && 
          OAA_CI.rule_properties_dialog.rule_properties) {
        OAA_CI.rule_properties_dialog.rule_properties.update(rule_result);
      }

      if (this.textbox_rule_result_message) {
        this.textbox_rule_result_message.setAttribute('value', rule_summary_item.rule_result.getMessage());
      }  

    }
    else {

      label = this.nls_strings.getString('noRuleSelected');

      this.button_rule_info.setAttribute("label", this.nls_strings.getString('rule') + ' ' + this.nls_strings.getString('information'));
      this.button_rule_info.setAttribute("tooltiptext",  label);
      this.button_rule_info.setAttribute("disabled", "true");
      
      if (OAA_CI.rule_properties_dialog && 
          OAA_CI.rule_properties_dialog.rule_properties) {
        OAA_CI.rule_properties_dialog.rule_properties.clear();
      }

    }
  
  }  
};

/**
 * @function OAA_CI.RuleSummaryView.showRuleSummaryReport
 *
 * @desc Opens a new tab in the window to display an HTML view of the rule summary report
 */
 
OAA_CI.RuleSummaryView.showRuleSummaryReport = function () {

  if (!this.filtered_rule_summary) return;

  var dir = FileUtils.getDir('TmpD', [], true, true);

  var file = FileUtils.getFile('TmpD', ['report_rule_summary.html']);
  
  var fileStream = FileUtils.openSafeFileOutputStream(file, 0x02 | 0x08 | 0x20, 0644, 0);  
  
  var html = this.filtered_rule_summary.toHTML(this.sidebar_name);
  
  fileStream.write(html, html.length);
  
  FileUtils.closeSafeFileOutputStream(fileStream);
    
  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Report Rule Summary URL: " + file.path);
 
  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
    .getInterface(Components.interfaces.nsIWebNavigation)
    .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
    .rootTreeItem
    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
    .getInterface(Components.interfaces.nsIDOMWindow);
    
  mainWindow.gBrowser.addTab(file.path);

  file = FileUtils.getFile('TmpD', ['report_rule_summary.csv']);
  
  fileStream = FileUtils.openSafeFileOutputStream(file, 0x02 | 0x08 | 0x20, 0644, 0);  
  
  var csv = this.filtered_rule_summary.toCSV(this.sidebar_name);
  
  fileStream.write(csv, csv.length);
  
  FileUtils.closeSafeFileOutputStream(fileStream);

};

